package com.xiaomaoguai.tac.cloud.apm.logging.logback.sensitive.service.impl;

import com.xiaomaoguai.tac.cloud.apm.logging.logback.SensitiveDataRule;
import com.xiaomaoguai.tac.cloud.apm.logging.logback.sensitive.SensitiveDataRuleManager;
import com.xiaomaoguai.tac.cloud.apm.logging.logback.sensitive.service.SensitiveDataRuleService;
import org.apache.commons.lang3.StringUtils;

import java.util.Collections;
import java.util.Iterator;
import java.util.Set;

/**
 * @author WeiHui-Z
 * @version v1.0.0
 * @date 2019/7/27 14:34
 * @since JDK 1.8
 */
public class SensitiveDataRuleServiceImpl implements SensitiveDataRuleService {

	/**
	 * 初始化加载一些默认的 脱敏规则 ，注意可以被动态 脱敏规则 覆盖
	 *
	 * @param sensitiveDataRules 默认脱敏规则
	 */
	@Override
	public void initLoadSensitiveDataRule(Set<SensitiveDataRule> sensitiveDataRules) {
		SensitiveDataRuleManager.dataRules.addAll(sensitiveDataRules);
	}

	/**
	 * 增加一个脱敏规则
	 *
	 * @param sensitiveDataRule 脱敏规则
	 * @return true-增加成功
	 */
	@Override
	public boolean addSensitiveDataRule(SensitiveDataRule sensitiveDataRule) {
		return SensitiveDataRuleManager.dataRules.add(sensitiveDataRule);
	}

	/**
	 * 删除一个脱敏规则
	 *
	 * @param fieldName 脱敏字段
	 * @return true-删除成功
	 */
	@Override
	public boolean deleteSensitiveDataRule(String fieldName) {
		boolean result = false;
		Iterator<SensitiveDataRule> iterator = SensitiveDataRuleManager.dataRules.iterator();
		while (iterator.hasNext()) {
			SensitiveDataRule sensitiveDataRule = iterator.next();
			if (StringUtils.equals(sensitiveDataRule.getFieldName(), fieldName)) {
				iterator.remove();
				result = true;
			}
		}
		return result;
	}

	/**
	 * 清除所有脱敏规则
	 */
	@Override
	public void clearAll() {
		SensitiveDataRuleManager.dataRules.clear();
	}

	/**
	 * 查询现在生效的所有默认规则
	 *
	 * @return 所有脱敏规则
	 */
	@Override
	public Set<SensitiveDataRule> getAllSensitiveDataRule() {
		return Collections.unmodifiableSet(SensitiveDataRuleManager.dataRules);
	}

}
